<template>
  <div class="search">
    <!-- 搜索按钮 -->
    <van-search
      v-model="value"
      show-action
      placeholder="请输入搜索关键词"
      @input="thinkClick"
      @search="onSearch"
      @cancel="onCancel"
      background="#3296fa"
    />
    <!-- 联想区域 -->
    <van-cell-group v-if="thinkList.length != 0">
      <van-cell title="联想区域" />
      <van-cell v-for="(item, index) in thinkList" :key="index" @click="onSearch(item.oldItem)" icon="search">
        <template #title>
          <div v-html="item.newItem"></div>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 历史搜索 -->
    <van-cell-group v-else>
      <van-cell title="历史搜索区域">
        <template #default>
          <van-icon @click="delAll" name="delete" />
        </template>
      </van-cell>
      <van-cell :title="item" @click="onSearch(item)" v-for="(item, index) in historyList" :key="index" icon="search">
        <template #default>
          <van-icon @click.stop="delHistory(index)" name="cross" />
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getThinkData } from '@/api/search.js'
import { localSet, localGet, localRemove } from '@/utils/local.js'

export default {
  data () {
    return {
      value: '',
      // 联想区域数据
      thinkList: [],
      timer: null,
      historyList: localGet('history') || [] // 历史区域
    }
  },
  methods: {
    onSearch (val) {
      this.$router.push(`/searchResult/${val}`)

      this.historyList.unshift(val)
      // 数组去重
      this.historyList = [...new Set(this.historyList)]
      // 保存到本地
      localSet('history', this.historyList)
    },
    onCancel () {
      console.log('onCancel')
    },
    // 输入内容时触发input事件
    thinkClick (val) {
      console.log(val)
      // 非空判断
      if (val.trim() === '') {
        this.thinkList = []
        return
      }
      // 进行js防抖操作
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        const res = await getThinkData(val)
        // console.log('联想：', res)
        this.thinkList = res.data.options
        // 关键字高亮
        this.thinkList = this.thinkList.map(item => {
          return {
            newItem: item.replace(val, `<span style="color: red">${val}</span>`),
            oldItem: item
          }
        })
      }, 300)
    },
    // 删除历史搜索
    delHistory (index) {
      this.historyList.splice(index, 1)
      // 保存到本地
      localSet('history', this.historyList)
    },
    // 删除所有历史数据
    delAll () {
      this.$dialog.confirm({
        title: '提示',
        message: '确定要清空历史记录吗？？？'
      })
        .then(() => {
          // on confirm
          this.historyList = []
          // 删除本地存储
          localRemove('history')
        })
        .catch(() => {
          // on cancel
        })
    }
  }
}
</script>

<style lang="less" scoped>
.search{
  .van-search__action{
    color: #fff;
  }

  .van-search__action:active {
    color: #f78;
  }
}
</style>
